//
//  AnswerView.swift
//  vr
//
//  Created by 李旭峰 on 2020/7/17.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa

class AnswerView: NSObject {
    private let dispose = DisposeBag()
    static let viewName:String = "plugins.com.asman/answer"
    private let frame:CGRect
    private let viewID:Int64
    private let args:Any?
    var messenger:FlutterBinaryMessenger
    private var channel:FlutterMethodChannel?
    private var isDidInit:Bool = false
    
    private let myView:AsmanLiteView
    private let emptyView:UIView = UIView()

    init(_ frame:CGRect,viewID:Int64,args:Any?,binaryMessenger:FlutterBinaryMessenger) {
        self.frame = frame
        self.viewID = viewID
        self.args = args
        self.messenger = binaryMessenger
        let tempArgs = args as? [String:Any] ?? [:]
        let schemeInfoDetailData:[String:Any] = (tempArgs["schemeInfoDetailData"] as? String ?? "").toJson()
        let token = String.SwitchToString(tempArgs["token"]) ?? "0"
        let schemeId = String.SwitchToString(tempArgs["schemeId"]) ?? "0"
        let roomId = String.SwitchToString(tempArgs["roomId"])?.decimal.uint32Value ?? 0
        let headUrl = String.SwitchToString(tempArgs["headUrl"]) ?? "https://img.asman.com.cn/assets/1575555291735_75384.png"
        let name = String.SwitchToString(tempArgs["name"]) ?? ""
        let userId = String.SwitchToString(tempArgs["userId"]) ?? "0"
        let accountId = String.SwitchToString(tempArgs["accountId"])
        let groupId = String.SwitchToString(tempArgs["groupId"]) ?? "0"
        let vrType = String.SwitchToString(tempArgs["vrType"])?.decimal.int
        let sdkAppId = String.SwitchToString(tempArgs["sdkAppId"]) ?? ""
        let userSig = String.SwitchToString(tempArgs["userSig"]) ?? ""
        let params = AsmanLiteViewModel.InitialParams(userId: userId,
                                                      accountId: accountId,
                                                      roomId: roomId,
                                                      headUrl: headUrl,
                                                      name: name,
                                                      schemeId: schemeId,
                                                      groupId: groupId,
                                                      vrType: vrType)
        self.myView = AsmanLiteView(withInitialParams: params,
                                    token:token,
                                    sdkAppId:sdkAppId,
                                    userSig: userSig,
                                    schemeInfoDetailData:schemeInfoDetailData)
        super.init()
        self.myView.delegate = self
    }
    private func initMathodChannel(){
        let channel = FlutterMethodChannel.init(name: "plugins.com.asman/answer_\(self.viewID)", binaryMessenger: self.messenger)
        self.channel = channel
        self.channel?.setMethodCallHandler({[weak self] (call, result) in
            guard let `self` = self else  { return }
            switch call.method {
            case "answerSuccess":
                self.myView.answerSuccess {
                    result("")
                }
            case "answerFail":
                self.myView.answerFail  {
                    result("")
                }
            case "answerError":
                self.myView.answerError  {
                    result("")
                }
            default:result("");
            }
        })
    }

    private func initEmptyView(){
        self.emptyView.frame = self.frame
        self.emptyView.backgroundColor = UIColor.gray
        let textField = UITextField()
        textField.textColor = UIColor.purple
        textField.backgroundColor = UIColor.white
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.keyboardType = UIKeyboardType.numberPad
        self.emptyView.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(40)
        }
        let btn = UIButton(type: .custom)
        btn.setTitle("send", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.backgroundColor = UIColor.blue
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        self.emptyView.addSubview(btn)
        btn.snp.makeConstraints { (make) in
            make.centerY.height.equalTo(textField)
            make.leading.equalTo(textField.snp.trailing).offset(10)
            make.width.equalTo(60)
            make.trailing.equalToSuperview().offset(-20)
        }
        btn.rx.tap.subscribe(onNext: {[weak self] in
            guard let `self` = self else { return }
            let height = textField.text?.decimal.cgfloat ?? 0
        }).disposed(by: self.dispose)
    }
    deinit {
        print("Answer View did deinit")
    }
}

extension AnswerView : FlutterPlatformView {
    func view() -> UIView {
        if !self.isDidInit {
            self.isDidInit = true
            self.initMathodChannel()
        }
        return self.myView
    }
    
}
extension AnswerView : AsmanLiteViewDelegate {
    
    func router3DRoam() {
        self.channel?.invokeMethod("router3DRoam", arguments: [:]);
    }
    
    func rejectAnswer() {
        self.channel?.invokeMethod("rejectAnswer", arguments: [:]);
    }
    func getTrtcAuthInfo() {
        self.channel?.invokeMethod("getTrtcAuthInfo", arguments: [:]);
    }
    func notifyDesignerJoined(){
        self.channel?.invokeMethod("notifyDesignerJoined", arguments: [:]);
    }
    func canReceived(_ params: String) {
        self.channel?.invokeMethod("canReceived", arguments: params);
    }
    
    func answer(_ params: String) {
        self.channel?.invokeMethod("answer", arguments: params);
    }
}
